import { renderStream } from '@/utils/lib';
import styled from '@emotion/styled';
import React, { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useStream } from '../Context/StreamContext';
import useSyncState from '../hooks/useSyncState';

const Container = styled.div``;

interface VideoItemProps {
	id: string | undefined;
	label: string;
	audioOnly: boolean;
	clientId: string;
	videoId: string;
	muteStatus: boolean;
	streamMode: string;
	role: string;
	isScreenSyncMode: boolean;
	userName: string;
}

const TTSVideo = (props: VideoItemProps) => {
	const { id, label } = props;

	const { session } = useSelector((state: any) => state);

	const { renderTTSStream, setRenderTTSStream } = useStream();

	useEffect(() => {
		if (renderTTSStream().find((ele: any) => ele.id === id)) {
			renderTTSStream().forEach((ele: any) => {
				if (ele.id === id) {
					let video = document.getElementById(ele.id) as HTMLVideoElement;
					video!.srcObject = ele.stream;
					video!.play();
				}
			});
			return;
		}
		id && render(label, id);
	}, [id]);

	const render = async (label: string, videoId: string) => {
		try {
			const data = await renderStream(label, videoId, (data: any) => {});
			console.log(data, 'render tts stream success');
			let video = document.getElementById(id!) as HTMLVideoElement;
			setRenderTTSStream([...renderTTSStream(), { id: id, stream: video!.srcObject }]);
		} catch (error) {
			console.log(error, 'render tts stream error');
		}
	};

	return (
		<Container>
			<video className="tts-streams" x5-video-player-type="h5" controlsList="nodownload nofullscreen" playsInline autoPlay id={id} muted={false}></video>
		</Container>
	);
};

export default TTSVideo;
